package com.harvest.scientific.ladder.util

import android.view.View
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.concurrent.ConcurrentHashMap

object VcUtil {
    private const val DEFAULT_CLICK_FREQUENCIES_TIME = 600L // 默认限频时长

    private val lastClickTimeMap: MutableMap<Int, Long> = ConcurrentHashMap()

    private val coroutinescope by lazy {  CoroutineScope(Dispatchers.IO) }

    @JvmStatic
    @JvmOverloads
    fun isFastDoubleClick(view: View?, timeA: Long = DEFAULT_CLICK_FREQUENCIES_TIME): Boolean {
        if (view == null) {
            return false
        }
        val viewId = view.id
        val lastClickTime =  lastClickTimeMap[viewId]?: 0
        val currentTimeMillis = System.currentTimeMillis()
        if (currentTimeMillis - lastClickTime > timeA) {
            lastClickTimeMap[viewId] = currentTimeMillis
            coroutinescope.launch {
                delay(timeA)
                if (lastClickTimeMap[viewId] == currentTimeMillis){
                    lastClickTimeMap.remove(viewId)
                }
            }
            return false
        }
        return true
    }

}